package cn.geekyspace.scanhive.controller.web;

import cn.geekyspace.scanhive.pojo.entity.CleaningData;
import cn.geekyspace.scanhive.pojo.query.OutsideQueryData;
import cn.geekyspace.scanhive.pojo.vo.CleaningDataVO;
import cn.geekyspace.scanhive.service.CleaningDataService;
import cn.geekyspace.scanhive.utils.R;
import jakarta.annotation.Resource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

@RestController
public class ApplicationController {
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Resource
    private CleaningDataService cleaningDataService;

    @GetMapping("/hello")
    public String hello() {
        return "欢迎使用 JavaFX 与 Spring Boot！" + System.getProperty("java.home");
    }

    @PostMapping("/outside/v1/dataList")
    public R<List<CleaningDataVO>> dataList(@Validated @RequestBody OutsideQueryData outsideQueryData) {
        LocalDateTime startTime, endTime;
        try {
            startTime = LocalDateTime.parse(outsideQueryData.getStartTime(), df);
            endTime = LocalDateTime.parse(outsideQueryData.getEndTime(), df);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("时间格式错误，仅支持yyyy-MM-dd HH:ss:mm格式");
        }
        List<CleaningData> list = cleaningDataService.lambdaQuery()
                .ge(CleaningData::getQrCodeScanTime, startTime)
                .le(CleaningData::getQrCodeScanTime, endTime)
                .orderByDesc(CleaningData::getQrCodeScanTime)
                .list();
        List<CleaningDataVO> result = list.stream().map(e -> new CleaningDataVO().builder(e)).toList();
        return R.success(result);
    }
}
